package exercise17;

import java.awt.*;
import java.awt.event.*;
import java.io.FileNotFoundException;

import javax.swing.*;
import javax.swing.border.*;
import chapter17.Histogram;

public class Exercise17_5 extends JFrame{

	private JLabel jlbTextFile = new JLabel("Text File");
	private JTextArea jtaResult = new JTextArea();
	private JTextField jtfInput = new JTextField("F:\\JStudy\\JavaBase\\src\\chapter17\\ButtonDemo.java");
	private Histogram histogram = new Histogram();
	private Border lineborder = new LineBorder(Color.BLACK, 1);
	
	
	public static void main(String[] args) {
		Exercise17_5 frame = new Exercise17_5();
		frame.setTitle("Exercise17_5");
		frame.setSize(700, 200);
		frame.setLocationRelativeTo(null);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);

	}
	
	private int[] countLetters(){
		int[] count = new int[26];
		String text = jtaResult.getText();
		for (int i = 0; i < text.length(); i++) {
			char character = text.charAt(i);
			if ((character >= 'A') && (character <= 'Z')) {
				count[character - 'A']++;
			}
			else if ((character >= 'a') && (character <= 'z')) {
				count[character - 'a']++;
			}
		}
		return count;
	}
	
	
	public Exercise17_5 (){
		setLayout(new BorderLayout(5, 5));
		
		JPanel jpInput = new JPanel(new FlowLayout(FlowLayout.LEFT));
		jpInput.add(jlbTextFile);
		jpInput.add(jtfInput);
		jpInput.setBorder(lineborder);
		jlbTextFile.setFont(new Font("TimesRoman", Font.BOLD, 14));
		histogram.setBorder(lineborder);
		
		add(histogram, BorderLayout.CENTER);
		add(jpInput, BorderLayout.SOUTH);
		
		jtfInput.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					Exercise17_4.displayText(jtfInput.getText(), jtaResult);
				} catch (FileNotFoundException e1) {
//					e1.printStackTrace();
					System.out.println("File isn't exists!");
				}
				
				int[] count = countLetters();
				histogram.showHistogram(count);
			}
		});
		
	}

}
